import { useState, useEffect } from "react";
import { notifications } from "./base";
//const URL = "http://localhost:3001/";
//const URL = "http://47.99.157.36:3001/api/";
//const URL = "http://192.168.2.127:3001/api/";
const URL = "http://localhost:3002/api/";
//const URL = "http://47.99.157.36:3002/api/";

// let isRun = false;
// let intervalId;
// let url = "/login";

// can not let inside the App,which will run many times
export function Relogin(props) {
  const counter = props?.counter || 3;
  const [state, setState] = useState({
    counter: counter,
    message: "please login...",
  });
  useEffect(() => {
    if (state.counter > 0) {
      notifications.show(state.counter);
      setTimeout(() => {
        setState((pre) => ({
          counter: pre.counter - 1,
          message: pre.counter === 1 ? "goto login page..." : pre.message,
        }));
        //      console.log("inside", state);
      }, 1000);
    } else {
      //outsize,start,
      //then , 5 4 3 2 1
      window.location.href = "/login";
      notifications.show(state.message);
    }
  }, [state]);

  return (
    <div id="Relogin">
      {state.counter} [ {state.message} ]
    </div>
  );
}
const api = new (class {
  constructor() {
    this.token = localStorage.getItem("token") || null;
    this.res = {};
    this.ok = false;
  }

  async setRes(res) {
    this.res = await res.json();
    this.res.status = res.status;
    this.res.ok = res.status === 200;
    console.log("web api:", this.res);
  }

  setError(message = "Network error.") {
    this.ok = false;
    this.res.message = message;
  }

  async post(data, url) {
    //console.log("post:", data);
    try {
      const res = await fetch(URL + url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "bearer " + this.token,
        },
        body: JSON.stringify(data),
        credentials: "include", // 设置为 'include' 启用凭证发送
      });
      await this.setRes(res);
    } catch (e) {
      console.error(e);
      this.setError();
    }
  }
  async get(data, url) {
    //console.log("post:", data);
    try {
      // change to json to url params
      const queryString = new URLSearchParams(data).toString();
      const fullUrl = URL + url + queryString;
      const res = await fetch(fullUrl, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: "bearer " + this.token,
        },
        credentials: "include", // 设置为 'include' 启用凭证发送
      });
      await this.setRes(res);
    } catch (e) {
      console.error(e);
      //network?
      this.setError("can not connect to server.");
    }
  }

  async login(user) {
    await this.post({ user: user }, "login");
    //this.token = this.ok ? this.res.token : null;
    localStorage.setItem("token", this.res.token || null);
    localStorage.setItem("user", this.res.user || null);
    return this.res;
  }

  async getData(type, params = {}) {
    await this.get(
      {
        type: type,
        ...params,
      },
      "getData?",
    );
    return this.res;
  }

  //top api
  async getTableNames() {
    await this.getData("tableNames");
    return this.res;
  }

  async queryTable(tableName, params = {}) {
    await this.getData("queryTable", {
      tableName: tableName,
      ...params,
    });
    return this.res;
  }

  getPersonInfo() {
    return localStorage.getItem("user");
  }

  async getPersonList(selectNames = "*") {
    await this.getData("personList", {
      select: selectNames,
    });
    return this.res;
  }

  async getDataOld(params) {
    const queryString = new URLSearchParams(params).toString();
    const url = URL + "getData?" + queryString;
    const res = await fetch(url);
    const data = await res.json();
    if (res.ok) {
      //
      // console.log("123 web DT: data get succeessfully")
      // console.log({...data})
      return data;
    } else {
      // 处理请求失败的情况
      console.error("123 web DT:  Failed to get data. ");
      console.log(data);
      switch (res.status) {
        case 400:
          throw new Error("前端请求出错啦，快叫前端同学来看看");
        case 401:
          throw new Error(data.message);
        case 500:
          throw new Error("服务器出错啦，快叫后端同学来看看");
        default:
          throw new Error("web DT: server 未知错误");
      }
    }
  }

  deleteTable(params) {
    return this.getData(params);
  }
})();

export default api;
